#!/usr/bin/env php
<?php

require __DIR__.'/../vendor/autoload.php';

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Question\ChoiceQuestion;

$application = new Application();

class SnippetGeneratorCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('snippet')
            ->setDescription('Generate your snippet.')
        ;
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $projectDir = dirname(__FILE__) . '/../';

        $helper = $this->getHelper('question');
        $snippetQuestion = new Question('Please enter your snippet name: ');
        $snippetQuestion->setValidator(function ($value) {
            if (trim($value) == '') {
                throw new \Exception('The snippet name cannot be empty');
            }

            return $value;
        });
        $snippetName = $helper->ask($input, $output, $snippetQuestion);

        $tags = json_decode(file_get_contents($projectDir . 'data/tags.json'), true);
        $snippetTagsQuestion = new ChoiceQuestion(
            'Please select snippet tags: ',
            pluck($tags, 'name')
        );
        $snippetTagsQuestion->setMultiselect(true);
        $snippetTags = $helper->ask($input, $output, $snippetTagsQuestion);

        $snippetTemplate = file_get_contents($projectDir . 'scripts/snippet-template.md');
        $snippetTemplate = str_replace('snippetName', $snippetName, $snippetTemplate);
        file_put_contents($projectDir . 'snippets/' . $snippetName . '.md', $snippetTemplate);
        $database = json_decode(file_get_contents($projectDir . 'data/database.json'));
        $database->{$snippetName} = array_map('strtolower', $snippetTags);
        file_put_contents($projectDir . 'data/database.json', json_encode($database));

        $output->writeln("Your snippet has been generated at snippets/{$snippetName}.md");
    }
}

$application->add(new SnippetGeneratorCommand());

$application->run();
